package com.wzl.kgmusic

import android.annotation.SuppressLint
import android.media.AudioFormat
import android.media.AudioRecord
import android.media.MediaRecorder
import android.os.Bundle
import android.widget.Button
import androidx.appcompat.app.AppCompatActivity
import com.arthenica.mobileffmpeg.FFmpeg
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import java.io.File
import java.io.FileOutputStream

class MainActivity : AppCompatActivity(), Callback {
    var isPlayType = false
    private var mController: Controller? = null
    private var isRecording = false
    private var accompanimentPath: String = ""
    private var recordedFile: File? = null
    private var mergePath1: String = ""
    private var mergePath2: String = ""
    private var mp3Path: String = ""

    @SuppressLint("MissingInflatedId")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        findViewById<Button>(R.id.button).setOnClickListener {
            start()
        }
        findViewById<Button>(R.id.button1).setOnClickListener {
            isPlayType = !isPlayType
            mController!!.openOriginalSinging(isPlayType)
        }
        findViewById<Button>(R.id.button2).setOnClickListener {
            stopRecording()
        }

    }

    private fun start() {
        accompanimentPath =
            Utils.getRecoderPath("accompaniment.id" + "_rec_" + System.currentTimeMillis() + ".pcm")
        mController = Controller(
            this,
            this,
            Utils.copyFile(this, "十年.m4a"),
            Utils.copyFile(this, "十年.mp3"),
            accompanimentPath
        )
        mController!!.start()
        initAudioRecord()
    }

    override fun onPlayerTime(ms: Long) {

    }

    private var audioRecord: AudioRecord? = null
    @SuppressLint("MissingPermission")
    private fun initAudioRecord() {
        val sampleRate = 44100 // 采样率
        val channelConfig = AudioFormat.CHANNEL_IN_STEREO
        val audioFormat = AudioFormat.ENCODING_PCM_16BIT // 16 位 PCM 编码
        val bufferSize = AudioRecord.getMinBufferSize(sampleRate, channelConfig, audioFormat)

        audioRecord = AudioRecord(
            MediaRecorder.AudioSource.VOICE_COMMUNICATION,
            sampleRate,
            channelConfig,
            audioFormat,
            bufferSize
        )
        audioRecord?.startRecording()
        isRecording = true
        CoroutineScope(Dispatchers.IO).launch {
            recordAudioData(bufferSize)
        }
    }

    private fun recordAudioData(bufferSize: Int) {
        val buffer = ByteArray(bufferSize)
        val imageDir = Utils.getMusicDir()
        recordedFile = File("$imageDir/recorded_audio.pcm")
        val outputStream = FileOutputStream(recordedFile)
        while (isRecording) {
            val read = audioRecord?.read(buffer, 0, bufferSize) ?: 0
            if (read > 0) {
                outputStream.write(buffer, 0, read)
            }
        }
        outputStream.flush()
        outputStream.close()
    }

    private fun stopRecording() {
        isRecording = false
        audioRecord?.stop()
        audioRecord?.release()
        audioRecord = null
        // 处理录制的音频文件
        processRecordedAudio()
    }

    private fun processRecordedAudio() {
        mergePath1 =
            Utils.getRecoderPath("recordedFile.id" + "_rec_" + System.currentTimeMillis() + ".wav")
        mergePath2 =
            Utils.getRecoderPath("accompaniment.id" + "_rec_" + System.currentTimeMillis() + ".wav")
        val recordedFile = arrayOf<String>(
            "-f",
            "s16le",
            "-ar",
            "44100",
            "-ac",
            "2",
            "-i",
            recordedFile?.absolutePath!!,
            mergePath1
        )
        FFmpeg.execute(recordedFile)
        val accompaniment = arrayOf<String>(
            "-f",
            "s16le",
            "-ar",
            "44100",
            "-ac",
            "2",
            "-i",
            accompanimentPath,
            mergePath2
        )
        FFmpeg.execute(accompaniment)

        mp3Path =
            Utils.getRecoderPath("mp3Path.id" + "_rec_" + System.currentTimeMillis() + ".wav")
        val cmd = arrayOf(
            "-i", mergePath1,
            "-i", mergePath2,
            "-filter_complex", "amix=inputs=2:duration=first:dropout_transition=3",
            mp3Path
        )
//        PCMFileMerger.mergePCMFiles(
//            recordedFile?.absolutePath,
//            accompanimentPath,
//            mergePath
//        )





//
//        val ffmpegCommand = arrayOf<String>(
//            "-f",
//            "s16le",
//            "-ar",
//            "44100",
//            "-ac",
//            "2",
//            "-i",
//            mergePath,
//            mp3Path
//        )

        val execute = FFmpeg.execute(cmd)
        println()
    }
}